package com.yumo.kangchenjunga.activity;

import java.util.Optional;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import com.yumo.kangchenjunga.company.CompanyEntity;
import com.yumo.kangchenjunga.company.CompanyService;
import com.yumo.kangchenjunga.company.CompanyVo;

@Controller
public class ActivityPageController {

	@Autowired
	private ActivityService activityService;
	@Autowired
	private CompanyService companyService;

	@GetMapping("/admin/activities")
	public String page(Model model, HttpServletRequest request,
			@PageableDefault(page = 0, size = 10, sort = "id", direction = Direction.DESC) Pageable pageable) {
		Activity activity = new Activity();
		CompanyVo companyVo = new CompanyVo();

		activity.title = request.getParameter("title");
		companyVo.id = Optional.ofNullable(StringUtils.trimToNull(request.getParameter("companyId")))
				.map(Integer::valueOf).orElse(null);
		activity.company = new CompanyEntity(companyVo);

		model.addAttribute("activities", activityService.query(activity, pageable));
		model.addAttribute("companies", companyService.list());
		model.addAttribute("search", activity);
		return "admin/activity";
	}

	@GetMapping("/activities")
	public String page2(Model model, HttpServletRequest request,
			@PageableDefault(page = 0, size = 10, sort = "id", direction = Direction.DESC) Pageable pageable) {
		Activity activity = new Activity();
		CompanyVo companyVo = new CompanyVo();

		activity.title = request.getParameter("title");
		companyVo.id = Optional.ofNullable(StringUtils.trimToNull(request.getParameter("companyId")))
				.map(Integer::valueOf).orElse(null);
		activity.company = new CompanyEntity(companyVo);

		model.addAttribute("activities", activityService.query(activity, pageable));
		model.addAttribute("companies", companyService.list());
		model.addAttribute("search", activity);
		return "admin/activity2";
	}

}
